package com.yunshipei.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemClock;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by cike on 15-11-4.
 */
public class PhoneInfo {
    private TelephonyManager tm;
    private WindowManager windowManager;
    private WifiManager wifiManager;
    private ConnectivityManager cm;
    private PackageManager pm;
    private Context mContext;

    public PhoneInfo(Context context) {
        tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        pm = context.getPackageManager();
        mContext = context.getApplicationContext();
    }

    /**
     * 获取IMEI
     *
     * @return
     */
    public String getIMEI() {
        return tm.getDeviceId();
    }

    /**
     * h获取屏幕分辨率
     *
     * @return
     */
    public String getWindowWiHeight() {
        Display dis = windowManager.getDefaultDisplay();
        return new StringBuffer().append(dis.getWidth()).append("x").append(dis.getHeight()).toString();
    }

    /**
     * 获取Mac地址
     *
     * @return
     */
    public String getMacAddress() {
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo.getMacAddress() != null)
            return wifiInfo.getMacAddress();
        return null;
    }

    /**
     * 获取开机时长
     *
     * @return
     */
    public long getStartTime() {
        return SystemClock.elapsedRealtime() / 1000;
    }

    /**
     * 获取CPU序列号
     *
     * @return
     */
    public String getCPUSerial() {
        String str = "", strCPU = "", cpuAddress = "0000000000000000";
        try {
            //读取CPU信息
            Process pp = Runtime.getRuntime().exec("cat /proc/cpuinfo");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            //查找CPU序列号
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    //查找到序列号所在行
                    if (str.indexOf("Serial") > -1) {
                        //提取序列号
                        strCPU = str.substring(str.indexOf(":") + 1,
                                str.length());
                        //去空格
                        cpuAddress = strCPU.trim();
                        break;
                    }
                } else {
                    //文件结尾
                    break;
                }
            }
        } catch (Exception ex) {
            //赋予默认值
            ex.printStackTrace();
        }
        return cpuAddress;
    }

    /**
     * 判断当前手机是否有ROOT权限
     *
     * @return
     */
    public boolean isRoot() {
        boolean bool = false;
//        try {
//            if ((!new File("/system/bin/su").exists()) && (!new File("/system/xbin/su").exists())) {
//                bool = false;
//            } else {
//                bool = true;
//            }
//        } catch (Exception e) {
//
//        }
        bool = new Root().isDeviceRooted();
        return bool;
    }

    /**
     * 获取手机型号
     *
     * @return
     */
    public String getPhoneModel() {
        if (Build.MODEL.indexOf(Build.MANUFACTURER) != 0)
            return android.os.Build.MANUFACTURER + " " + android.os.Build.MODEL;
        return Build.MODEL;
    }

    /**
     * 获取手机运营商
     *
     * @return
     */
    public String getOperator() {
        String imsi = tm.getSubscriberId();

        if (imsi != null) {

            if (imsi.startsWith("46000") || imsi.startsWith("46002")) {
                //因为移动网络编号46000下的IMSI已经用完，所以虚拟了一个46002编号，134/159号段使用了此编号 //中国移动
                return "中国移动";
            } else if (imsi.startsWith("46001")) {
                //中国联通
                return "中国联通";
            } else if (imsi.startsWith("46003")) {
                //中国电信
                return "中国电信";
            }
        }
        return "未安装sim卡";
    }

    /**
     * 系统版本
     *
     * @return
     */
    public String getSystemVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 内核版本
     *
     * @return
     */
    public static String getKernelVersion() {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec("cat /proc/version");

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String kernelVersion = "";
        InputStream inputStream = null;
        inputStream = process.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream), 8 * 1024);
        String info = "";
        String line = "";
        try {
            while ((line = bufferedReader.readLine()) != null) {
                info += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            if (info != "") {
                final String keyword = "version ";
                int index = info.indexOf(keyword);
                line = info.substring(index + keyword.length());
                index = line.indexOf(" ");
                kernelVersion = line.substring(0, index);
            }
        } catch (IndexOutOfBoundsException e) {
            e.printStackTrace();
        }

        return kernelVersion;
    }

    public String getPhoneNums() {
        String phone = "";
        phone = tm.getLine1Number();
        return phone;
    }

    public String getSubscriberId() {
        return tm.getSubscriberId();
    }

    /**
     * 移动网络状态
     *
     * @return
     */
    public String getNetStatus() {
        String netStatus = "";
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.getType() == ConnectivityManager.TYPE_MOBILE) {
            switch (ni.getSubtype()) {
                case TelephonyManager.NETWORK_TYPE_UMTS:
                case TelephonyManager.NETWORK_TYPE_HSUPA:
                    //联通2G
                    netStatus = "3G";
                    break;
                case TelephonyManager.NETWORK_TYPE_GPRS:
                case TelephonyManager.NETWORK_TYPE_EDGE:
                    //移动 联通2G
                    netStatus = "2G";
                    break;
                case TelephonyManager.NETWORK_TYPE_CDMA:
                    //电信2G
                    netStatus = "2G";
                    break;
                case TelephonyManager.NETWORK_TYPE_EVDO_0:
                    //电信3G
                    netStatus = "3G";
                    break;
                case TelephonyManager.NETWORK_TYPE_LTE:
                    //各个运营商
                    netStatus = "4G";
                    break;
                default:
                    Log.e("网络类型", "" + ni.getSubtype());
                    netStatus = "移动网络状态未知";
                    break;

            }
        } else if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {
            netStatus = "WIFI";
        } else {

            netStatus = "获取失败";
        }
        return netStatus;
    }

    public List<String> getApps() {
        List<String> list = new ArrayList<>();
        List<ApplicationInfo> apps = pm.getInstalledApplications(0);
        for (ApplicationInfo info : apps) {
            list.add(info.packageName);
        }
        return list;
    }


    //=========================   root权限判断 start   ===============================
    public static class Root {

        private static String LOG_TAG = Root.class.getName();

        public boolean isDeviceRooted() {
            if (checkRootMethod1()) {
                return true;
            }
            if (checkRootMethod2()) {
                return true;
            }
            if (checkRootMethod3()) {
                return true;
            }
            return false;
        }

        public boolean checkRootMethod1() {
            String buildTags = android.os.Build.TAGS;

            if (buildTags != null && buildTags.contains("test-keys")) {
                return true;
            }
            return false;
        }

        public boolean checkRootMethod2() {
            try {
                File file = new File("/system/app/Superuser.apk");
                if (file.exists()) {
                    return true;
                }
            } catch (Exception e) {
            }

            return false;
        }

        public boolean checkRootMethod3() {
            if (new ExecShell().executeCommand(ExecShell.SHELL_CMD.check_su_binary) != null) {
                return true;
            } else {
                return false;
            }
        }
    }


    public static class ExecShell {

        private static String LOG_TAG = ExecShell.class.getName();

        public static enum SHELL_CMD {
            check_su_binary(new String[]{"/system/xbin/which", "su"}),;

            String[] command;

            SHELL_CMD(String[] command) {
                this.command = command;
            }
        }

        public ArrayList<String> executeCommand(SHELL_CMD shellCmd) {
            String line = null;
            ArrayList<String> fullResponse = new ArrayList<String>();
            Process localProcess = null;

            try {
                localProcess = Runtime.getRuntime().exec(shellCmd.command);
            } catch (Exception e) {
                return null;
                //e.printStackTrace();
            }

            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(localProcess.getOutputStream()));
            BufferedReader in = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));

            try {
                while ((line = in.readLine()) != null) {
                    Log.d(LOG_TAG, "--> Line received: " + line);
                    fullResponse.add(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            Log.d(LOG_TAG, "--> Full response was: " + fullResponse);

            return fullResponse;
        }
    }

    //================================   root权限判断 end   ====================================

    public String getAppVersion() {
        try {
            return "Enterplorer " + pm.getPackageInfo(mContext.getPackageName(),0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    private static int DEVICEINFO_UNKNOWN = 1;
    /**
     * 获取cpu核心数
     */
    public static int getNumberOfCpuCOres() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1){
            // Gingerbread doesn't support giving a single application access to both cores, but a
            // handful of devices (Atrix 4G and Droid X2 for example) were released with a dual-core
            // chipset and Gingerbread; that can let an app in the background run without impacting
            // the foreground application. But for our purposes, it makes them single core.
            return 1;
        }
        int cores;
        try {
            cores = new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).length;
        } catch (SecurityException e) {
            cores = DEVICEINFO_UNKNOWN;
        } catch (NullPointerException e) {
            cores = DEVICEINFO_UNKNOWN;
        }
        return cores;
    }

    private static final FileFilter CPU_FILTER = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            String path = pathname.getName();
            if (path.startsWith("cpu")) {
                for (int i = 3; i < path.length(); i++) {
                    if (path.charAt(i) < '0' || path.charAt(i) >'9')
                        return false;
                }
                return true;
            }
            return false;
        }
    };


}
